import * as Cesium from 'cesium'
import { CircleWaveMaterialProperty } from './CircleWaveMaterialProperty.js'

/**
 * 无人机图标颜色枚举
 * 0: 类型A (例如：个人)
 * 1: 类型B (例如：企业)
 * 2: 类型C (例如：政府)
 */
export const colorOwner = {
  0: '#E0BD0CFF',
  1: '#07f5cc',
  2: '#43b4ff'
}

/**
 * 无人机图层类
 */
export default class UavModelLayer {

  // 无人机轨迹点的最大值限制
  maxPositions = 10

  MIN_DISPLAY_DISTANCE = 4000 // 设置最小显示距离为4000米

  constructor(Viewer, uavLayer) {
    this.viewer = Viewer
    this.uavLayer = uavLayer
    this.uavIconUrl = ''
    this.uavModelUrl = '/model/SXY800.glb'
  }

  /**
   * 添加无人机icon,model,label
   * @param {*} uavObj 
   */
  addUav (uavObj) {
    const { snCode, initPostion, ownerType, productCode, speedNum, height, img } = uavObj
    // console.log('添加无人机', this.uavLayer);

    // 设置无人机位置
    const SampledPosition = new Cesium.SampledPositionProperty()
    SampledPosition.setInterpolationOptions({
      interpolationDegree: 1,
      interpolationAlgorithm: Cesium.LinearApproximation
    })
    SampledPosition.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD;
    SampledPosition.addSample(Cesium.JulianDate.fromDate(new Date()), Cesium.Cartesian3.fromDegrees(initPostion[0], initPostion[1], initPostion[2]))

    // 设置无人机id和信息
    const idText = productCode ? productCode : snCode.substring(4).split('-')[0];
    const infoText = `${speedNum}米/秒 ${height}米`;

    const velocityVector = new Cesium.VelocityVectorProperty(SampledPosition, true);
    const initialCartesian = Cesium.Cartesian3.fromDegrees(initPostion[0], initPostion[1], initPostion[2]);
    const enuTransform = Cesium.Transforms.eastNorthUpToFixedFrame(initialCartesian);
    const inverseEnu = new Cesium.Matrix4();
    Cesium.Matrix4.inverse(enuTransform, inverseEnu);
    const velocityEnu = new Cesium.Cartesian3();
    let heading = Cesium.Math.toRadians(0) // 设置无人机的航向角度为0度
    let pitch = Cesium.Math.toRadians(0) // 设置无人机的俯仰角度为0度
    let roll = Cesium.Math.toRadians(0) // 设置无人机的滚转角度为0度
    let hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll)

    const uavIcon = new Cesium.Entity({
      id: snCode,
      position: SampledPosition,
      orientation: new Cesium.CallbackProperty((time, result) => {
        const position = SampledPosition.getValue(time)
        const velocityEcef = velocityVector.getValue(time);

        if (!Cesium.defined(velocityEcef)) return undefined
        Cesium.Matrix4.multiplyByPointAsVector(inverseEnu, velocityEcef, velocityEnu);

        // 获取东北天坐标系中的速度分量
        const eastSpeed = velocityEnu.x;   // 东向速度
        const northSpeed = velocityEnu.y;  // 北向速度
        const upSpeed = velocityEnu.z;     // 垂直向上速度

        const horizontalSpeed = Math.abs(Math.sqrt(eastSpeed * eastSpeed + northSpeed * northSpeed));
        const verticalSpeed = Math.abs(upSpeed);

        // 水平运动
        if (Math.round(horizontalSpeed) && !Math.round(verticalSpeed)) {
          hpr.heading = -Math.atan2(northSpeed, eastSpeed);
        }
        // this.updateUavPopupPos({
        //   snCode,
        //   position
        // })
        return Cesium.Transforms.headingPitchRollQuaternion(
          position,
          hpr,
          Cesium.Ellipsoid.WGS84,
          Cesium.Transforms.eastNorthUpToFixedFrame,
          result
        );
      }, false),
      model: {
        uri: this.uavModelUrl,
        minimumPixelSize: 64,
        scale: 1.0,
        // 添加近距离显示条件：只在0-500米范围内显示模型
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 500),
        color: new Cesium.Color(1.0, 1.0, 1.0, 1.0)  // 修改透明度为1.0，使模型可见
      },
      billboard: {
        image: img,
        scale: 1.0,
        heightReference: Cesium.HeightReference.NONE,
        clampToGround: false, // 是否贴地
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        // 添加距离缩放效果：近距离(0-100000)保持原始大小1.0，远距离(150000米)缩小到0.3
        scaleByDistance: new Cesium.NearFarScalar(100000, 1.0, 150000, 0.3),
        // 只在远距离(超过500米)显示billboard
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(500, 2000000),
      },
      label: {
        text: `${idText}\n${infoText}`,
        font: '32px Microsoft YaHei Bold',
        scale: 0.5,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        fillColor: Cesium.Color.fromCssColorString('#FFFFFF'),
        outlineColor: Cesium.Color.fromCssColorString(colorOwner[ownerType]),
        outlineWidth: 5,
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        pixelOffset: new Cesium.Cartesian2(20, -10),
        heightReference: Cesium.HeightReference.NONE,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        // 只在远距离(超过500米)显示label
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(500, 150000),
        // 可以根据需要调整垂直对齐方式
        verticalOrigin: Cesium.VerticalOrigin.CENTER
      },
      ellipse: {
        show: false,
        semiMinorAxis: 500,
        semiMajorAxis: 500,
        material: new CircleWaveMaterialProperty({
          duration: 4000,
          // color: "#00FF00" // 绿色
        }),
      }
    })

    this.viewer.entities.add(uavIcon)

    this.uavLayer.set(snCode, {
      uavIcon,
      // popUp: this.createPopup(uavObj),
      alarmWave: undefined
    })
  }

  /**
   * 判断是否存在无人机
   * @param {*} snCode 
   * @returns 
   */
  hasUav (snCode) {
    return this.uavLayer.has(snCode)
  }

  /**
   * 更新无人机信息
   * @param {*} uavObj 
   * @returns 
   */
  updateUavInfo (uavObj) {
    const { snCode, ownerType, productCode, speedNum, height, img, flightStatus, position } = uavObj

    if (this.hasUav(snCode)) {
      const uavItem = this.uavLayer.get(snCode)

      // 更新无人机图标上的信息
      const idText = productCode ? productCode : snCode.substring(4).split('-')[0]
      const infoText = `${speedNum}米/秒 ${height}米`
      uavItem.uavIcon.label.text = `${idText}\n${infoText}`
      uavItem.uavIcon.label.outlineColor = Cesium.Color.fromCssColorString(colorOwner[ownerType])
      uavItem.uavIcon.label.fillColor = Cesium.Color.fromCssColorString('#FFFFFF')
      uavItem.uavIcon.billboard.image = img

      // 更新无人机广告牌的信息
      // const popup = uavItem.popUp;
      // if (popup && popup.style.display !== 'none') {
      //   // 只有当广告牌可见时才更新内容
      //   // 更新背景图片（根据告警状态）
      //   const bgImage = flightStatus ? '/img/alram-tip-red.png' : '/img/alram-tip-blue.png';
      //   popup.style.background = `url('${bgImage}') no-repeat center center`;
      //   popup.style.backgroundSize = '100% 100%';

      //   // 更新内容字段
      //   const snCodeElem = popup.querySelector('#uav-snCode');
      //   const speedNumElem = popup.querySelector('#uav-speedNum');
      //   const heightElem = popup.querySelector('#uav-height');
      //   const productCodeElem = popup.querySelector('#uav-productCode');
      //   const statusElem = popup.querySelector('#uav-status');

      //   if (snCodeElem) snCodeElem.textContent = snCode || '';
      //   if (speedNumElem) speedNumElem.textContent = speedNum || 0;
      //   if (heightElem) heightElem.textContent = height || 0;
      //   if (productCodeElem) productCodeElem.textContent = productCode || '';

      //   if (statusElem) {
      //     statusElem.textContent = flightStatus ? '告警' : '正常';
      //     statusElem.style.color = flightStatus ? '#ff4d4f' : '#52c41a';
      //   }
      // }

      // 计算无人机到摄像机的距离,只显示当前最近无人机的告警状态
      let cartesian3 = Cesium.Cartesian3.fromDegrees(position[0], position[1], position[2])
      const cameraPosition = this.viewer.camera.position;
      const distance = Cesium.Cartesian3.distance(cartesian3, cameraPosition);
      if (distance > this.MIN_DISPLAY_DISTANCE) {
        uavItem.uavIcon.ellipse.show = false
      } else {
        uavItem.uavIcon.ellipse.show = flightStatus ? true : false
      }
      return true
    }
    return false
  }

  /**
   * 更新无人机广告牌的信息
   * @param {*} uavObj 
   */
  updateUavPopupPos (uavObj) {
    const { snCode, position } = uavObj;
    if (this.hasUav(snCode)) {
      const uavItem = this.uavLayer.get(snCode);

      let cartesian3;
      if (position instanceof Cesium.Cartesian3) {
        cartesian3 = position;
      } else {
        cartesian3 = Cesium.Cartesian3.fromDegrees(position[0], position[1], position[2]);
      }

      const popup = uavItem.popUp;
      const cartesian2 = Cesium.SceneTransforms.worldToWindowCoordinates(
        this.viewer.scene,
        cartesian3
      );

      const cameraPosition = this.viewer.camera.position;
      const distance = Cesium.Cartesian3.distance(cartesian3, cameraPosition);

      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;

      const isInView = cartesian2 &&
        cartesian2.x >= 0 &&
        cartesian2.x <= windowWidth &&
        cartesian2.y >= 0 &&
        cartesian2.y <= windowHeight;

      if (isInView && distance <= this.MIN_DISPLAY_DISTANCE) {
        if (!popup.parentNode) {
          document.body.appendChild(popup);
        }
        popup.style.display = 'block';

        let rightPos = cartesian2.x;
        let bottomPos = cartesian2.y;

        popup.style.left = `${rightPos - 300}px`;
        popup.style.top = `${bottomPos - 200}px`;

      } else {
        popup.style.display = 'none';
        if (popup.parentNode) {
          document.body.removeChild(popup);
        }
      }
    }
  }

  /**
   * 移动无人机
   * @param {*} uavObj 
   * @returns 
   */
  moveUav (uavObj) {
    const { snCode, position } = uavObj

    if (this.hasUav(snCode)) {
      const uavItem = this.uavLayer.get(snCode)

      // 移动无人机icon
      const currentTime = Cesium.JulianDate.fromDate(new Date())
      const futureTime = Cesium.JulianDate.addSeconds(currentTime, 2, new Cesium.JulianDate())
      const p = Cesium.Cartesian3.fromDegrees(position[0], position[1], position[2])
      uavItem.uavIcon.position.addSample(futureTime, p)

      // 清除历史轨迹点,防止内存泄漏
      const property = uavItem.uavIcon.position
      if (property._property && property._property._times && property._property._values) {
        while (property._property._times.length > this.maxPositions) {
          property._property._times.shift()
          // _values每次移除3个（x, y, z）
          property._property._values.shift()
          property._property._values.shift()
          property._property._values.shift()
        }
      }
      return true
    }
    return false
  }

  /**
   * 无人机广告牌
   * @returns 
   */
  createPopup (uavObj) {
    const { snCode, speedNum, height, productCode, flightStatus } = uavObj;

    // 创建弹出框
    const popup = document.createElement('div');
    popup.className = 'popup';

    // 根据飞行状态选择背景图片
    const bgImage = flightStatus ? '/img/alram-tip-red.png' : '/img/alram-tip-blue.png';

    // 设置样式
    popup.style.cssText = `
      background: url('${bgImage}') no-repeat center center;
      background-size: 100% 100%;
      padding: 18px;
      min-width: 250px;
      color: white;
      position: absolute;
      transform: translate(0, 0);
      will-change: transform;
      z-index: 10;
      display: none;
    `;

    // 添加内容，包含更多信息字段
    popup.innerHTML = `
      <div class="popup-content">
        <p style="padding-left: 20px;"><span style="color:#07f5cc;">编号:</span> <span id="uav-snCode">${snCode || ''}</span></p>
        <p style="padding-left: 20px;"><span style="color:#07f5cc;">速度:</span> <span id="uav-speedNum">${speedNum || 0}</span> 米/秒</p>
        <p style="padding-left: 20px;"><span style="color:#07f5cc;">高度:</span> <span id="uav-height">${height || 0}</span> 米</p>
        <p style="padding-left: 20px;"><span style="color:#07f5cc;">型号:</span> <span id="uav-productCode">${productCode || ''}</span></p>
        <p style="padding-left: 20px;"><span style="color:#07f5cc;">状态:</span> 
          <span id="uav-status" style="color:${flightStatus ? '#ff4d4f' : '#52c41a'}">
            ${flightStatus ? '告警' : '正常'}
          </span>
        </p>
      </div>
    `;

    return popup;
  }
}